package com.ux.iot.jetlinks.service.auth;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ux.iot.jetlinks.bo.JetlinkResult;
import com.ux.iot.jetlinks.bo.LoginInfo;
import com.ux.iot.jetlinks.pro.AuthProperties;
import com.ux.iot.jetlinks.util.NetUtilsTool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * token 管理器
 * @date 2021/11/15 11:16
 */
@Slf4j
@AllArgsConstructor
public class JetlinkTokenManager {
    AuthProperties authProperties;
    static LoginInfo loginInfo;
    /**
     * 获取token
     * @return
     */
    public  LoginInfo getToken() throws Exception {
        if(ObjectUtil.isEmpty(loginInfo)){
            if(ObjectUtil.isEmpty(authProperties)){
                log.error("授权配置信息为空");
                return null;
            }
            Map<String,Object> param=new HashMap<>();
            param.put("username", authProperties.getUsername());
            param.put("password", authProperties.getPassword());
            param.put("tokenType",authProperties.getTokenType());
            param.put("expires",authProperties.getExpires());
                String result= NetUtilsTool.unHeaderPost(authProperties.getUrl()+"/authorize/login", JSON.toJSONString(param));
                JetlinkResult<LoginInfo> re=JSON.parseObject(result,new TypeReference<JetlinkResult<LoginInfo>>(LoginInfo.class){});
                loginInfo =re.getResult();
                return re.getResult();
        }else {
            return loginInfo;
        }
    }

}
